package com.dana.gomoku.api;

import com.dana.gomoku.constant.Constants;
import com.dana.gomoku.match.MatchRequest;
import com.dana.gomoku.match.MatchResponse;
import com.dana.gomoku.match.Matcher;
import com.dana.gomoku.match.OnlineUserManager;
import com.dana.gomoku.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
@Slf4j
public class MatchAPI extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;
    @Autowired
    Matcher matcher;
    private ObjectMapper mapper=new ObjectMapper();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
       try {
           //获取对象
           User user = (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
           log.info("获取到对象为 {}",user.getUsername());
           //防止一个用户重复登录--"多开问题"
           if (onlineUserManager.getFromGameHall(user.getUserId())!=null||
                   onlineUserManager.getFromGameRoom(user.getUserId())!=null){
               MatchResponse response=new MatchResponse();
               response.setOk(false);
               response.setReason("当前用户已经登录");
               response.setMessage("repeatConnection");
               session.sendMessage(new TextMessage(mapper.writeValueAsString(response)));
               session.close();
           }
           //建立连接之后将玩家设置成为上线
           onlineUserManager.enterGameHall(user.getUserId(), session);
           log.info("玩家 {} 进入游戏大厅",user.getUsername());
       }catch (NullPointerException e){
           System.out.println("[afterConnectionEstablished] 空指针异常");
       }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //获取对象
        User user = (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
        String payload = message.getPayload();
        MatchRequest request=mapper.readValue(payload, MatchRequest.class);
        MatchResponse response=new MatchResponse();
        if (request.getMessage().equals("startMatch")){
            response.setMessage("startMatch");
            response.setOk(true);
            matcher.add(user);
        }else if (request.getMessage().equals("stopMatch")){
            response.setOk(true);
            response.setMessage("stopMatch");
            matcher.remove(user);
        }else {
            response.setReason("IllegalException");
            response.setOk(false);
        }
        session.sendMessage(new TextMessage(mapper.writeValueAsString(response)));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
       try {
           //获取对象
           User user = (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
           if (user==null){
               log.warn("会话 {} 的 User 对象为空", session.getId());
               return;
           }
           WebSocketSession tepSession = onlineUserManager.getFromGameHall(user.getUserId());
           if (tepSession==session){
               onlineUserManager.exitGameHall(user.getUserId());
               log.info("玩家 {} 离开游戏大厅",user.getUsername());
           }
           matcher.remove(user);
       }catch (NullPointerException e){
           System.out.println("[handleTransportError] 空指针异常");
       }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            //获取对象
            User user = (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
            if (user==null){
                log.warn("会话 {} 的 User 对象为空", session.getId());
                return;
            }
            WebSocketSession tepSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tepSession==session){
                onlineUserManager.exitGameHall(user.getUserId());
                log.info("玩家 {} 离开游戏大厅",user.getUsername());
            }
            matcher.remove(user);
        }catch (NullPointerException e){
            System.out.println("[handleTransportError] 空指针异常");
        }
    }
}
